import { getUserInfo } from '@/api/user'
import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router/index'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo:{}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state:object) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state:any, token:string) => {
    state.token = token
  },
  SET_USERINFO:(state:any, userInfo:any) => {
    state.userInfo = userInfo
  },
}

const actions = {
  // user login
  login(state:any, form:any) {
    return new Promise((resolve, reject) => {
      login(form).then((response:any) => {
        const { data } = response
        state.commit('SET_TOKEN', data.token)
        setToken(data.token)
        state.dispatch('userInfo')
        resolve(data)
      }).catch((error:any) => {
        reject(error)
      })
    })
  },

  //user getUserInfo
  userInfo(state:any) {
    return new Promise((resolve, reject) => {
      getUserInfo().then((response:any) => {
        const { data } = response
        state.commit('SET_USERINFO', data)
        resolve(data)
      }).catch((error:any) => {
        reject(error)
      })
    })
  },


  // user logout
  logout(state:any) {
    removeToken() // must remove  token  first
    router.push({path:'/login'})
    state.commit('RESET_STATE')
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

